import { createAlova } from 'alova';
import adapterFetch from 'alova/fetch';
import VueHook from 'alova/vue';

function getCookie(name) {
  const cookies = document.cookie.split(";").map(cookie => cookie.trim());
  const foundCookie = cookies.find(cookie => cookie.startsWith(name + "="));
  return foundCookie ? decodeURIComponent(foundCookie.split("=")[1]) : null;
}


export const alovaInstance = createAlova({
  // baseURL: 'http://expertextractionservice:9090/expertextractionservice',
  baseURL: '/expertextractionservice',
  statesHook: VueHook,
  requestAdapter: adapterFetch(),
  cacheFor: null,
  shareRequest: true,
  beforeRequest: (method) => {
    // 从本地存储获取SSO Token
    const token = localStorage.getItem('access_token');
    // 如果Token存在，则添加Authorization头
    if (token) {
      method.config.headers = {
        ...method.config.headers,
        Authorization: `Bearer ${token}`
      };
    }
    // method.config.headers['Origin'] = 'http://expertextractionwebsite:9000'; // 允许所有来源
   //  method.config.headers['Access-Control-Allow-Origin'] = '*'; // 允许所有来源
    // method.config.headers['Access-Control-Allow-Methods'] = 'GET, POST,PUT,OPTIONS';
    // method.config.headers['Access-Control-Allow-Headers'] = 'Authorization, Content-Type'; 
    const csrfToken = getCookie("XSRF-TOKEN"); // 从 Cookie 读取 CSRF 令牌
    console.log('csrfToken',csrfToken)
    method.config.headers['X-CSRF-TOKEN']= csrfToken
  },
  responded: {
    onSuccess: async (response) => {     
      if (response.redirected) {
        const redirectUrl = response.url;
            console.log("302 重定向到:", redirectUrl);
            window.location.href =redirectUrl
        return []; // 重新请求新地址
      }
        // 获取Content-Type
        const contentType = response.headers.get('Content-Type');
        // 判断是否是JSON
        if (contentType && contentType.includes('application/json')) {  
          const data = await response.json(); // 解析JSON数据       
          if (!response.ok) {
            throw new Error(data.message || "未知错误");
          }
          return data;
        } else {
          const data = await response.text(); // 返回文本数据
          if (!response.ok) {
            throw new Error(data);
          }
          return data;
        }
    },
    onError: async (error, method) => {
      console.error('请求失败:', error);      
      // 处理Token过期情况
      if (error.status === 401) {
        console.warn('Access Token 失效，尝试刷新 Token...');
        const success = await refreshToken();
        if (success) {
          // 重新执行原始请求
          return method.send();
        }
      }
      // throw new Error(error);
      return Promise.reject(error); // 保证错误会进入 catch
    }
  }
});

export const alovaAuthServer = createAlova({
 // baseURL: '/',
  statesHook: VueHook,
  requestAdapter: adapterFetch(),
  cacheFor: null,
  shareRequest: true,
  beforeRequest: (method) => {
    // 从本地存储获取SSO Token
    const token = localStorage.getItem('access_token');
    // 如果Token存在，则添加Authorization头
    if (token) {
      method.config.headers = {
        ...method.config.headers,
        Authorization: `Bearer ${token}`
      };
    }
    // method.config.headers['Origin'] = 'http://expertextractionwebsite:9000'; // 允许所有来源
   //  method.config.headers['Access-Control-Allow-Origin'] = '*'; // 允许所有来源
    // method.config.headers['Access-Control-Allow-Methods'] = 'GET, POST,PUT,OPTIONS';
    // method.config.headers['Access-Control-Allow-Headers'] = 'Authorization, Content-Type'; 

    const csrfToken = getCookie("XSRF-TOKEN"); // 从 Cookie 读取 CSRF 令牌
    console.log('csrfToken',csrfToken)
    method.config.headers['X-CSRF-TOKEN']= csrfToken
  },
  responded: {
    onSuccess: async (response) => {
        // 获取Content-Type
        const contentType = response.headers.get('Content-Type');
        // 判断是否是JSON
        if (contentType && contentType.includes('application/json')) {  
          const data = await response.json(); // 解析JSON数据       
          if (!response.ok) {
            throw new Error(data.message || "未知错误");
          }
          return data;
        } else {
          const data = await response.text(); // 返回文本数据
          if (!response.ok) {
            throw new Error(data);
          }
          return data;
        }
    },
    onError: async (error, method) => {
      console.error('请求失败:', error);      
      // 处理Token过期情况
      if (error.status === 401) {
        console.warn('Access Token 失效，尝试刷新 Token...');
        const success = await refreshToken();
        if (success) {
          // 重新执行原始请求
          return method.send();
        }
      }
      throw new Error(error);
    }
  }
});

// 刷新 Token 逻辑
const refreshToken = async () => {
  try {
    const refreshToken = localStorage.getItem('refresh_token');
    if (!refreshToken) {
      console.error('Refresh Token 不存在，用户需要重新登录');
      return false;
    }

    const response = await fetch('http://authserver:9999/auth/refresh-token', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${refreshToken}`
      }
    });

    if (response.ok) {
      const data = await response.json();
      localStorage.setItem('access_token', data.access_token);
      return true;
    } else {
      console.error('Token 续期失败，请重新登录');
      return false;
    }
  } catch (error) {
    console.error('刷新 Token 发生错误:', error);
    return false;
  }
};